/**
 * Copyright (C), 2001-2031, www.bosssof.com.cn
 * FileName: Enum.java
 * Author: YuXingZh
 * Date: 16/5/2024 上午10:42
 * Description:
 * <p>
 * History:
 * Date          Author   Version  Desc
 * 2024-01-01    bosssoft  1.0.0   initialize this file
 */
package org.boss.util;

import org.boss.strategy.JsonParseStrategy;
import org.boss.strategy.XmlParseStrategy;

import javax.crypto.*;
import java.io.IOException;
import java.net.SocketAddress;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;


/**
 * @className: protocol
 * @description: 解决什么问题：文件工具类
 * @author: YuXingZh
 * @date: 15/5/2024下午10:38
 * @since 1.0
 **/
public class FileUtil {


    /**
     * 根据文件类型选择密钥。
     *
     * @param filePath 文件路径
     * @return 密钥字符串
     */
    public static String chooseKeyByFileType(String filePath) {
        String fileExtension = getFileExtension(filePath);
        switch (fileExtension) {
            case "xml":
                return XmlParseStrategy.getInstance().parse("xml");
            case "json":
                return JsonParseStrategy.getInstance().parse("json");
            default:
                throw new IllegalArgumentException("不支持的文件类型");
        }
    }

    /*
     * 获取文件扩展名。
     *
     * @param filePath 文件路径
     * @return 文件扩展名
     */
    public static String getFileExtension(String filePath) {
        int dotIndex = filePath.lastIndexOf('.');
        if (dotIndex > 0 && dotIndex < filePath.length() - 1) {
            return filePath.substring(dotIndex + 1).toLowerCase();
        } else {
            throw new IllegalArgumentException("不支持的文件类型");
        }
    }


    /*
     * 读取文件
     * @author YuXingZh
     * @date 2024/05/17 08:29
     *
     * @param filePath
     * @return byte[]
     */
    public static byte[] readFile(String filePath) throws IOException {
        return Files.readAllBytes(Paths.get(filePath));
    }


    /*
     * 写入文件
     * @author YuXingZh
     * @date 2024/05/17 08:29
     *
     * @param filePath
     * @param content
     * @return void
     */
    public static void writeFile(String filePath, byte[] content) throws IOException {
        Files.write(Paths.get(filePath), content);
    }

    /**
     * 生成一个对称密钥
     * @author YuXingZh
     * @date 2024/05/17 08:30
     *
     * @param
     * @return SecretKey
     */
    public static SecretKey generateSecretKey() throws NoSuchAlgorithmException {
        KeyGenerator keyGen = KeyGenerator.getInstance("AES");
        keyGen.init(128);
        return keyGen.generateKey();
    }

    /*
     * 加密内容
     * @author YuXingZh
     * @date 2024/05/17 08:30
     *
     * @param content
     * @param key
     * @return byte[]
     */
    public static byte[] encrypt(byte[] content, SecretKey key) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.ENCRYPT_MODE, key);
        return cipher.doFinal(content);
    }

    /*
     * 解密内容
     * @author YuXingZh
     * @date 2024/05/17 08:30
     *
     * @param content
     * @param key
     * @return byte[]
     */
    public static byte[] decrypt(byte[] content, SecretKey key) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.DECRYPT_MODE, key);
        return cipher.doFinal(content);
    }

    /**
     * 创建以store+客户端端口号命名的文件夹。
     *
     * @param socketAddress 客户端的 SocketAddress
     * @throws IOException 如果文件操作失败
     */
    public static void createFileStore(SocketAddress socketAddress) throws IOException {
        // 获取客户端端口号
        int port = ((java.net.InetSocketAddress) socketAddress).getPort();

        // 获取当前工作目录的Path对象
        Path currentWorkingDirectory = Paths.get(".\\store");

        // 创建文件夹名称，使用store+端口号命名
        String folderName = "store" + port;

        // 创建文件夹的完整路径
        Path folderPath = currentWorkingDirectory.resolve(folderName);

        // 如果文件夹不存在，创建它
        if (!Files.exists(folderPath)) {
            Files.createDirectories(folderPath);
        }
    }
}
